package net.fdukedom.epicurus.client.plugin.core.panels;

import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.util.ResourceBundle;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import net.fdukedom.epicurus.client.ClientSession;
import net.fdukedom.epicurus.client.connection.MessageServiceWrapper;
import net.fdukedom.epicurus.client.plugin.core.CoreClientPlugin;
import net.fdukedom.epicurus.client.ui.GUIDispatcher;
import net.fdukedom.epicurus.client.ui.GridBagJPanel;
import net.fdukedom.epicurus.domain.entity.User;
import net.fdukedom.epicurus.domain.util.UserHelper;
import net.fdukedom.epicurus.resource.ResourceDispatcher;
import net.fdukedom.epicurus.service.interaction.IdentificationRequest;
import net.fdukedom.epicurus.service.interaction.IdentificationRequestWriter;
import net.fdukedom.epicurus.service.interaction.ProfileXMLWrapper;
import net.fdukedom.epicurus.service.interaction.ResponseReader;

public class LoginPanel extends GridBagJPanel {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Email text field
	 */
	private JTextField emailField;

	/**
	 * Password field
	 */
	private JPasswordField passwordField;

	/**
	 * Do login action
	 * 
	 * @author Alexander Kirakozov
	 */
	private class LoginAction extends AbstractAction {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public void actionPerformed(ActionEvent arg0) {
			ResourceBundle bundle = ResourceDispatcher.getInstance().getBundle(
					"bundles.ApplicationResources");
			User user = UserHelper.getInstance().findByEmail(
					emailField.getText());

			if (user != null) {
				if (user.getPassword().equals(
						User.hash(passwordField.getText()))) {
					ClientSession.getInstance().openSession(user.getId());
					GUIDispatcher.getInstance().showPage(null,
							GUIDispatcher.INDEX_PAGE_ID, null);
				} else {
					GUIDispatcher.getInstance().showInfoMessage(
							bundle.getString("login.errors.failed"));
				}
			} else {
				IdentificationRequestWriter request = new IdentificationRequestWriter(
						IdentificationRequest.ID_UPDATE);
				String passHash = User.hash(passwordField.getText());

				request.setPluginName(CoreClientPlugin.PLUGINNAME);
				request.setEmail(emailField.getText());
				request.setPassword(passHash);

				MessageServiceWrapper service = new MessageServiceWrapper();

				String xmlResponse = service.sendMessage(request.toString());
				ResponseReader reader = new ResponseReader(xmlResponse);

				if (reader.getStatus()) {
					ProfileXMLWrapper wrap = new ProfileXMLWrapper(reader
							.getResult().getChild(ProfileXMLWrapper.PROFILE));

					user = new User();

					user.setEmail(emailField.getText());
					user.setPassword(passHash);
					user.setSex(wrap.getSex());
					user.setName(wrap.getNickName());

					UserHelper.getInstance().saveUser(user);
					ClientSession.getInstance().openSession(user.getId());
					GUIDispatcher.getInstance().showPage(null,
							GUIDispatcher.INDEX_PAGE_ID, null);
				} else {
					GUIDispatcher.getInstance().showInfoMessage(
							reader.getMessage());
				}
			}
		}
	}

	/**
	 * Constructor
	 */
	public LoginPanel() {
		init();
	}

	/**
	 * Initialize method
	 */
	private void init() {
		ResourceBundle loginBundle = ResourceDispatcher.getInstance()
				.getBundle("bundles.pub.Login");

		// Fields
		final int[] widths = { 50, 50, 50, 50, 50 };
		final int[] heights = { 5, 20, 20, 20, 0 };
		final double[] yWeights = { 0, 0, 0, 1 };
		initLayout(null, widths, yWeights, heights);

		addComponent(new JLabel(loginBundle.getString("pub.login.email")), 1,
				0, 2, 1, GridBagConstraints.NORTH);
		emailField = new JTextField("");
		addComponent(emailField, 1, 2, 3, 1,
				GridBagConstraints.FIRST_LINE_START);

		addComponent(new JLabel(loginBundle.getString("pub.login.password")),
				2, 0, 2, 1, GridBagConstraints.FIRST_LINE_END);
		passwordField = new JPasswordField("");
		addComponent(passwordField, 2, 2, 3, 1,
				GridBagConstraints.FIRST_LINE_START);

		// Button
		JButton button = new JButton(loginBundle.getString("pub.login.doLogin"));
		button.addActionListener(new LoginAction());
		addComponent(button, 3, 1, 3, 1, GridBagConstraints.FIRST_LINE_START);
	}
}
